<?php

namespace App\Services\Http;

class HttpRequest
{
    private static $conn;

    //请求的token
    private $token;

    //请求url
    private $url;

    //请求的类型
    private $method;

    //请求的数据
    private $data;

    //curl实例
    private $curl;

    public $status;

    private $headers = array();

    private function __construct()
    {
        $method = 'get';
        $data = [];
        $url = "http://trading_api.ejing.com/backend/orders/1";
        if (!$url) {
            return false;
        }

        $this->method = strtolower($method);
        if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
            return false;
        }

        $paramUrl = '';
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $paramUrl .= $key . '=' . $value . '&';
            }
            $url = $url . '?' . $paramUrl;
        }

        //初始化类中的数据
        $this->url = $url;

        $this->data = $data;
        try {
            if (!$this->curl = curl_init()) {
                throw new Exception('curl初始化错误：');
            };
        } catch (Exception $e) {
            echo '<pre>';
            print_r($e->getMessage());
            echo '</pre>';
        }

        curl_setopt($this->curl, CURLOPT_URL, $this->url);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($this->curl, CURLOPT_TIMEOUT, 10); // 设置超时限制防止死循环
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
    }

    public static function getInstance(){
        if(!(self::$conn instanceof self)){
            self::$conn = new self;
        }
        return self::$conn;
    }

    public function __clone(){
        trigger_error('不能够复制');
    }

    /**
     * get 查询资源
     */
    public function _get()
    {

    }

    /**
     * post 新增资源
     */
    public function _post()
    {
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
    }

    /**
     * put 更新资源
     */
    public function _put()
    {
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
    }

    /**
     * delete 删除资源
     */
    public function _delete()
    {
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
    }

    /**
     * 执行发送请求
     */
    public function doRequest()
    {
        //发送给服务端验证信息，token根据参数走，所以此处暂时无用
        /*if((null !== $this->token) && $this->token){
            $this->headers = array(
                'Token: '.$this->token
            );
        }*/

        //发送头部信息
        $this->setHeader();

        //发送请求方式
        switch ($this->method) {
            case 'post':
                $this->_post();
                break;
            case 'put':
                $this->_put();
                break;
            case 'delete':
                $this->_delete();
                break;
            default:
                curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);
                break;
        }
        //执行curl请求
        $info = curl_exec($this->curl);
        $errno = curl_errno($this->curl);
        if ($errno == 0) {
            $curlInfo = $this->getInfo();
            $httpCode = $curlInfo['http_code'];
            if (200 == $httpCode) {
                $ret = json_decode($info, true);
                $ret = array_merge(['http_code' => 200], $ret);
                if (in_array($ret['code'], [900, 10, 11])) {
                    //@todo throw  new \App\Exceptions\NotLoginException();
                }
                return $ret;
            } else {
                $statusMsg = 'HttpCode:' . $httpCode;
            }
        }

        return [
            'http_code' => $httpCode,
            'code' => $statusMsg,
            'data' => $errno,
        ];
    }

    /**
     * 设置发送的头部信息
     */
    private function setHeader()
    {
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
    }

    /**
     * 获取curl中的状态信息
     */
    public function getInfo()
    {
        return curl_getinfo($this->curl);
    }

    /**
     * 关闭curl连接
     */
    public function __destruct()
    {
        curl_close($this->curl);
    }
}